﻿#include "medintuxParser.h"
#include "connexion.h"
#include "bmiManager.h"

#include <common/constants.h>
#include <common/settings.h>
#include <QSqlQuery>
#include <QSqlError>
#include <QTextDocumentFragment>
using namespace Constants;

medintuxParser::medintuxParser(QObject * parent)
{
    settings settings;
    if(CreateConnection() == false){
        QMessageBox::warning(0,QObject::trUtf8("Erreur"),
                             QObject::trUtf8("Connexion base de données impossible"),
                             QMessageBox::Ok);
        return;
       }
    m_db = QSqlDatabase::database(settings.value(Constants::DATABASE_DRTUX).toString());

    if(!m_db.isValid()){
        QMessageBox::warning(0,QObject::trUtf8("OK"),QObject::trUtf8("Database\n ")+m_db.databaseName(),QMessageBox::Ok);
        }
     QStringList args ;
     args = qApp->arguments();
     m_guid = "no guid";
     m_dateObs = QDate::currentDate();
     m_age     = "ousontpassesmesvingtans";
     m_sexe = "grrr";
     if(args.size() >3){
          m_guid = args[4];
          QString date = args[13];
          m_dateObs = QDate::fromString(date,"yyyy-MM-dd");
          qWarning () << args[13] << "arg 13 of medintux " << __FILE__ << QString::number(__LINE__);
          qWarning() << "guid = " << m_guid << " " << __FILE__ << QString::number(__LINE__);
          qWarning() << "date Obs = " << m_dateObs.toString("yyyy.MM.dd") << " " << __FILE__ << QString::number(__LINE__);
          }
    QStringList listAge;
    QString requeteAge    = "SELECT FchPat_Nee , FchPat_Sexe FROM fchpat WHERE FchPat_GUID_Doss = '"+m_guid+"'";
    QSqlQuery queryAge(m_db);
    if( !queryAge . exec (requeteAge)){
        qWarning() << __FILE__ << QString::number(__LINE__) << " " << queryAge.lastError().text();
        QMessageBox::information(0,QObject::trUtf8("Erreur"),QObject::trUtf8("queryAge = ")
                                 +QString::number(queryAge.numRowsAffected()),QMessageBox::Ok);
        }
    while(queryAge.next()){
        m_age = queryAge.value(0).toString();// date of birth "yyyy-MM-dd"
        m_sexe = queryAge.value(1).toString();
        listAge << m_age;
        }
}

medintuxParser::~medintuxParser(){}

QStandardItemModel * medintuxParser::inputOfDatas()
{
    QStandardItemModel * model = new QStandardItemModel(0,MaxDatasModelEnum);
    QString sex;
    QString dateOfBirth;
    QString today;
    QString dateOfObservation;
    QString weight;
    QString height;
    enum enumHeads {RBDATE_REFBLOBS_PRIMKEY=0, RBDATE_DATE};
    QStringList listBlobs;
    int key = 1;
    QString rechercheHeads  = "SELECT RbDate_RefBlobs_PrimKey , RbDate_Date FROM RubriquesHead "
                              "WHERE RbDate_TypeRub  = '20030000' AND RbDate_IDDos = '"+m_guid+"'";                              
    QSqlQuery query(m_db);
    if(!query.exec(rechercheHeads))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << " " << query.lastError().text();
        }
    QMap<QString,QString> mapDate;
    while(query.next()){
        QString   blobPrimkey   = query.value(RBDATE_REFBLOBS_PRIMKEY).toString();
        QString   strDate       = query.value(RBDATE_DATE).toString();
        if(strDate.contains("T")){
            QStringList lD = strDate.split("T");
            strDate = lD[0];
            }
        mapDate.insertMulti(strDate,blobPrimkey);
        }
    QMapIterator<QString,QString> itDate(mapDate);
    while(itDate.hasNext())
    {
        itDate.next();
        QSqlQuery queryBlobs(m_db);
        QString datesReq = QString("SELECT RbDate_DataRub FROM RubriquesBlobs WHERE RbDate_PrimKey = '"+itDate.value()+"'");                                   
        if(!queryBlobs.exec(datesReq))
        {                        
            qWarning() << __FILE__ << QString::number(__LINE__) << " " << queryBlobs.lastError().text();
            }
        while(queryBlobs.next())
        {
            QByteArray str1A  = queryBlobs.value(0).toByteArray();
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString strBlob   = codec->toUnicode(str1A);
            listBlobs        << strBlob;
            QTextDocumentFragment f ;
            f = QTextDocumentFragment::fromHtml(strBlob);
            QString blobInAString   = f.toPlainText();
            QStringList listBlobL ;
            if(blobInAString.contains("\n")){
                listBlobL  = blobInAString.split("\n");
                }
            else{listBlobL  << blobInAString;}
            QString poids = "zero";
            QString taille = "zero";
            QString date = itDate.key();
            for(int i = 0 ; i < listBlobL.size() ; i++) // on parse le blob observation ligne par ligne
            {
                if(listBlobL[i].contains("poids") && listBlobL[i].contains(":"))
                {
                    poids = listBlobL[i].split(":")[1].replace(" ","");
                    if(poids == "" || (poids.contains(QRegExp("[a-z]",Qt::CaseInsensitive))&& !poids.contains(QRegExp("("))))
                    {
                        poids="zero";
                        continue;
                        }// pas de courbe si pas de poids !
                    if (poids.contains(QRegExp("(")))
                    {
                        poids = poids.split("(")[0].replace(" ","");
                        }
                    }
                else if(listBlobL[i].contains("taille") && listBlobL[i].contains(":"))
                {
                    if (taille.isEmpty() )
                    {
                        for ( int i = model->rowCount(); i > -1; -- i)
                        {
                              QString lastheight = model->data(model->index(i,HEIGHT),Qt::DisplayRole).toString();
                              if (!lastheight.isEmpty())
                              {
                                    taille = height;
                                    break;
                                  }
                            }
                            if (taille.isEmpty())
                            {
                                  QMessageBox::warning(0,tr("Erreur"),tr("Pas de taille relevée pour ce patient."),QMessageBox::Ok); 
                                  return model;                                 
                                }
                        }
                    taille   = listBlobL[i].split(":")[1].replace(" ","");
                    }
                else
                {
                    qWarning() << "non poids non taille " << QString::number(__LINE__);
                    }
                }//for
            weight = poids;
            height = taille;
            dateOfObservation = date;
            today = QDate::currentDate().toString("yyyy-MM-dd");
            dateOfBirth = m_age;
            sex = m_sexe;
            QStandardItem * sexItem = new QStandardItem(sex);
            QStandardItem * ageItem = new QStandardItem(dateOfBirth);
            QStandardItem * todayItem = new QStandardItem(today);
            QStandardItem * dateItem = new QStandardItem(dateOfObservation);
            QStandardItem * weightItem = new QStandardItem(weight);
            QStandardItem * heightItem = new QStandardItem(height);
            QList<QStandardItem *> listofitems;
            listofitems << sexItem << ageItem << todayItem << dateItem << weightItem << heightItem;
            model->appendRow(listofitems);
            key++;
            }//while(queryBlobs.next())

    }//iterator

    return model;
}

QStandardItemModel *  medintuxParser::inputOfDatasInside(){//FIXME
    QStandardItemModel * model = new QStandardItemModel(0,MaxDatasModelEnum);
    QList<QMultiMap<int,QString> > rList;
    QMultiMap<int,QString> dateH,weightH,heightH;
    QString refHead;
    QString resultBlob;
    QString rechercheHeads        = "SELECT RbDate_RefBlobs_Primkey FROM RubriquesHead "
                                  "WHERE RbDate_TypeRub  = '20060000' AND RbDate_IDDos = '"+m_guid+"'";
    QSqlQuery qHead(m_db);
    if(!qHead.exec(rechercheHeads)){
        qWarning() << __FILE__ << QString::number(__LINE__) << " " << qHead.lastError().text();
        }
    while(qHead.next()){
        refHead = qHead.value(0).toString();
        }
    QString rechercheBlob = "SELECT RbDate_DataRub from RubriquesBlobs WHERE RbDate_PrimKey = '"+refHead+"'";
    QSqlQuery qBlob(m_db);
    if(!qBlob.exec(rechercheHeads)){
        qWarning() << __FILE__ << QString::number(__LINE__) << " " << qBlob.lastError().text();
        }
    while(qBlob.next()){
        resultBlob = qBlob.value(0).toString();
        }
    resultBlob = resultBlob.split("[VAR Poids]")[1];
    resultBlob = resultBlob.split("[VAR")[0];
    QStringList listPT;
    listPT = resultBlob.split("\n");
    QStringList resultDTP;
    QString str;
    foreach(str,listPT){
        if(!str.contains("Mod")){
            resultDTP << str;
            }
        }
    rList << dateH << weightH << heightH;  ;// date chosen
    return model;
}

